<?php

namespace api\modules\Wechat\modules\Sns\controllers;

use common\models\c2\entity\FeUserModel;
use common\models\c2\statics\FeUserType;
use common\rest\base\WxException;
use common\rest\statics\ResponseDatum;
use Yii;
use yii\web\Response;

/**
 * Default controller for the `sns` module
 */
class DefaultController extends \common\rest\controllers\Controller
{
    public $modelClass = "";

    /**
     * Renders the index view for the module
     * @return array
     */
    public function actionLogin()
    {
        // $access_token = \Yii::$app->wechat->getAssessToken($code);
        $wechatUser = \Yii::$app->wechat->oauth->user();
        $feUser = FeUserModel::findOne(['wechat_open_id' => $wechatUser->id]);
        if (!$feUser) {
            $attrs = [
                'type' => FeUserType::TYPE_WECHAT_REGISTRATION,
                'open_id' => $wechatUser->id,
                'wechat_open_id' => $wechatUser->id,
                'username' => $wechatUser->nickname,
                'registration_ip' => Yii::$app->request->userIP,
                'last_login_ip' => Yii::$app->request->userIP,
                'unconfirmed_email' => $wechatUser->avatar,
            ];
            $feUser = new FeUserModel();
            $feUser->loadDefaultValues();
            $feUser->setAttributes($attrs);
            $feUser->save();
        }
        return ResponseDatum::getSuccessDatum([], $feUser);
    }

}
